package com.wms.common.xss;

import com.wms.common.utils.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * XSS校验器
 */
public class XssValidator implements ConstraintValidator<Xss, String> {
    /**
     * 匹配HTML脚本正则表达式
     */
    private static final String HTML_PATTERN = "<(\\S*?)[^>]*>.*?|<.*? />";

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
//        空值直接通过校验
        if (StringUtils.isBlank(value)) {
            return true;
        }
        return !containsHtml(value);
    }

    /**
     * 检测输入字符串中是否包含HTML标签
     *
     * @param value
     * @return
     */
    public static boolean containsHtml(String value) {
        Pattern pattern = Pattern.compile(HTML_PATTERN);
        Matcher matcher = pattern.matcher(value);
//        全字符串匹配
        return matcher.matches();
    }
}
